from prettytable import PrettyTable
import matplotlib.pyplot as plt
import numpy as np
from scipy.special import factorial
from scipy.stats import hypergeom
from scipy.special import comb

def hypergeometric_distribution(N, K, n, x):
    numerator = comb(K, x) * comb(N - K, n - x)
    denominator = comb(N, n)
    probability = numerator / denominator
    return probability


def calculate_hypergeometric_quantiles(N, K, n, percentiles):
    # Вычисляем распределение
    distribution = [(x, hypergeometric_distribution(N, K, n, x)) for x in range(max(0, n - N + K), min(n, K) + 1)]
    quantiles = []

    for percentile in percentiles:
        cumulative_prob = 0
        # Ищем квантиль в отсортированном распределении
        for x, probability in distribution:
            cumulative_prob += probability
            if cumulative_prob >= percentile:
                quantiles.append(x)
                break

    return quantiles


# Пример использования
N = 20
K = 8
n = 12

percentiles = [0.25, 0.50, 0.75,0.95]

# Создаем таблицу
table = PrettyTable()
table.field_names = ["Percentile", "Quantile"]

quantiles = calculate_hypergeometric_quantiles(N, K, n, percentiles)

# Заполняем таблицу
for percentile, quantile in zip(percentiles, quantiles):
    table.add_row([f"{percentile}", quantile])

# Выводим таблицу
print(table)

table_bibl = PrettyTable()
table_bibl.field_names = ["p", "Quantile"]

# Создаем таблицу
table_bibl = PrettyTable()
table_bibl.field_names = ["Percentile", "Quantile"]

# Заполняем таблицу
for percentile in percentiles:
    quantile = hypergeom.ppf(percentile, N, K, n)
    table_bibl.add_row([f"{percentile}", quantile])

# Выводим таблицу
print(table_bibl)

bar_width=0.1

# Построение графика
plt.bar(percentiles, quantiles, bar_width, color='purple')
plt.xticks(percentiles)
plt.xlabel('P')
plt.ylabel('Квантили')
plt.title('Квантили Гипергеом. распред')
plt.show()


